﻿using System;
using System.Globalization;
using GammaJul.ReSharper.GammaXaml.Highlightings.Xaml;
using GammaJul.ReSharper.GammaXaml.Psi;
using GammaJul.ReSharper.GammaXaml.Psi.Xaml;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Intentions.Extensibility;
using JetBrains.ReSharper.Psi.Parsing;
using JetBrains.ReSharper.Psi.Xaml;
using JetBrains.ReSharper.Psi.Xml.Tree;
using JetBrains.Text;
using JetBrains.TextControl;

namespace GammaJul.ReSharper.GammaXaml.QuickFixes.Xaml {

	/// <summary>
	/// Bulb item that changes a Grid.Row or Grid.Column index.
	/// </summary>
	public class UseDefinitionItem : BulbActionBase {
		private readonly GridDefinitionValueOutOfRangeHighlighting _highlighting;
		private readonly int _definitionIndex;
		private readonly string _definitionSize;

		public int DefinitionIndex {
			get { return _definitionIndex; }
		}

		[CanBeNull]
		public string DefinitionSize {
			get { return _definitionSize; }
		}

		public override string Text {
			get {
				return String.Format(
					CultureInfo.CurrentCulture,
					"Use {0} {1} ({2}=\"{3}\")",
					_highlighting.DefinitionType.ToString(),
					_definitionIndex,
					_highlighting.DefinitionType.GetSizeString(),
					DefinitionSize ?? "?");
			}
		}
		
		protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress) {
			IXmlToken valueToken = _highlighting.ValueToken;
			var newToken = XmlTokenTypes.GetInstance<XamlLanguage>().TEXT.Create(new StringBuffer(_definitionIndex.ToString(CultureInfo.InvariantCulture)));
			valueToken = (IXmlToken) valueToken.ReplaceBy(newToken);
			valueToken.GetPsiServices().MarkAsDirty(valueToken.GetSourceFile());

			return null;
		}

		public UseDefinitionItem([NotNull] GridDefinitionValueOutOfRangeHighlighting highlighting, int definitionIndex, [CanBeNull] string definitionSize) {
			if (highlighting == null)
				throw new ArgumentNullException("highlighting");

			_highlighting = highlighting;
			_definitionIndex = definitionIndex;
			_definitionSize = definitionSize;
		}
	}
}